var currentDir	  = null;
var currentFile	  = null;
var msgbox		  = null;
var title		  = '';
var editorEnabled   = false;

var langs = {
    basic:'basic',
    c:'c',
    cpp:'cpp',
	css:'css',
	html:'html',
    shtml:'html',
	java:'java',
	js:'js',
	pas:'pas',
	php:'php',
    py:'python',
	rb:'ruby',
	sql:'sql',
	txt:'text',
	vb:'vb',
	xml:'xml'
};

jQuery(function($){
	msgbox = $('#msgbox');
	title = document.title;
	bindKey();
	listDir();
	$('#saveButton').click(function(){
		saveCurrentFile();
	});

	$('#newFileBtn').click(function(){
		var fileName = window.prompt("Input new file name please:");
        if(fileName != null && $.trim(fileName) != '') {
            newFile(fileName);
        }
	});
});


function listDir(dir) {
	dir = dir||'';
	$('#file_list').html('Opening...');
	var successCallback = renderDir;
	$.getJSON('fs.php',
		{action:'ls', val:dir},
		successCallback
	);
}

function openFile(file, lang) {
	lang = lang || 'text';
	$.get('fs.php',
		{action:'open', val:file},
		function(data) {
			//enableEditor();
			//myCpWindow.edit(data, lang);
            editAreaLoader.closeFile('myCpWindow', '_myfile_');
            editAreaLoader.openFile('myCpWindow', 
                                    {
                                        id:'_myfile_',
                                        syntax:lang,
                                        text:data,
                                        title:file
                                    });
			setCurrentFile(file);
		}
	);
}

function saveFile(content, file, isNew) {
	if(!file) {
		return;
	}
	msg('Saving...');
	//disableEditor();
	$.post('fs.php',
			{action:'save', val:file, content:content},
			function(data) {
				if(data == '0') {
					//enableEditor();
					msg('Saved on ' + new Date().toString());
				}
				else {
					//enableEditor();
					msg('Failed to save the file. Please try again.');
				}
			}
	);
}

function newFile(name) {
    if(!name) return;
    var self = this;
    $.get('fs.php',
          {action:'new', val:currentDir, name:name.toString()},
          function(data) {
              if(data == '1') {
                  self.listDir(self.currentDir);
                  msg('Created: ' + self.currentDir + '/' + name);
              }
              else {
                  msg('Failed to create file: ' + name);
              }
          }
    );
}

function saveCurrentFile() {
	saveFile(editAreaLoader.getValue("myCpWindow"), currentFile);
}

function bindKey() {
	$(window).keydown(function(event){
		if(event.keyCode==83 && event.ctrlKey) {
			saveCurrentFile();
			return false;
		}
	});
}

function handleFileClick(type, name) {
	switch(type) {
		case 'd':
			listDir(currentDir + '/' + name);
			break;

		case 'f':
			var lang = langs[getExt(name)];
			openFile(currentDir + '/' + name, lang);
			break;
	}
}

function getExt(name) {
    return name.substr(name.lastIndexOf('.')+1);
}

function renderDir(data) {
	currentDir = data.dir;
	var htmlStr = '';
	$.each(data.files, function(index, item){
		if(item.type == 'd')
		{
			htmlStr += "<span class='Dir' onclick='handleFileClick(\"d\","
			+"\""+item.name+"\");return false;'>" +
			item.name +  '</span><br />';
		}else{
			htmlStr += "<span class='File' onclick='handleFileClick(\"f\","
			+"\""+item.name+"\");return false;'>" +
			item.name +  '</span><br />';
		}
	});
	$('#file_list').html(htmlStr);
}

function msg(text) {
	if(!text) {
		msgbox.hide();
	}
	else {
		msgbox.html(text);
		msgbox.show();
	}
}

function setCurrentFile(file) {
	currentFile = file;
	file = file.replace(/^\/+/, '');
	document.title = title + ' - ' + file;
	$('#fileName').html('You are editing ' + file + ' now.');
}

function enableEditor() {
	if(!editorEnabled) {
			myCpWindow.toggleReadOnly();
	}
}
function disableEditor() {
	if(editorEnabled) {
			myCpWindow.toggleReadOnly();
	}
}

